package org.xmx0632.connector.protocol.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.xmx0632.connector.model.Gateway;
import org.xmx0632.connector.protocol.message.Heartbeat0002UpRequest;
import org.xmx0632.connector.protocol.message.Heartbeat0002UpResponse;
import org.xmx0632.connector.util.GlobalGateway;

@Component
public class Heartbeat0002UpRequestProcessor
		extends BaseMessageProcessor<Heartbeat0002UpRequest, Heartbeat0002UpResponse> {

	public static final Logger LOG = LoggerFactory.getLogger(Heartbeat0002UpRequestProcessor.class);

	@Override
	public Heartbeat0002UpResponse process(Heartbeat0002UpRequest message) {
		LOG.debug("handle invoked message:{}", message);
		String gatewayId = message.getGateway().getGatewayId();
		LOG.debug("gatewayId:{}", gatewayId);
		Gateway gateway = GlobalGateway.get(gatewayId);
		if (gateway == null) {
			// 没有发送注册消息,断开连接,返回null自动断开连接,见MessageProcessHandler.channelRead0
			LOG.debug("gatewayId:{} not found,disconnect client.", gatewayId);
			return null;
		}

		if (isExpired(message)) {
			LOG.debug("heartbeat isExpired:{},disconnect client.", message);
			return null;
		} else {
			// TODO 更新内存中的链接信息(超时时间),生成心跳响应消息
			return new Heartbeat0002UpResponse();
		}
	}

	// TODO 比较超时时间,判断心跳消息是否超时
	private boolean isExpired(Heartbeat0002UpRequest message) {
		return false;
	}
}
